package common

import (
	"github.com/lishimeng/go-log"
	"time"
)

type PageFunc func(token ...string) (nextToken string, err error)

type PageFuncV3 func(startIndex int, count int) (dataCount int, err error)

func TravelAmazonPage(pageFunc PageFunc, wait ...int64) {
	if pageFunc == nil {
		return
	}
	var err error
	var nextToken string
	nextToken, err = pageFunc()
	if err != nil {
		return
	}
	if len(nextToken) == 0 {
		return
	}
	for {
		nextToken, err = pageFunc(nextToken)
		if err != nil {
			break
		}
		if len(nextToken) == 0 {
			log.Info("no more data")
			break
		}
		if len(wait) > 0 {
			time.Sleep(time.Duration(wait[0]) * time.Millisecond)
		} else {
			time.Sleep(time.Second * 5)
		}
	}
}

func TravelAmazonPageV3(startWith, count int, pageFunc PageFuncV3, wait ...int64) {
	if pageFunc == nil {
		return
	}
	var err error
	var index int
	var respCount int
	index = startWith
	respCount, err = pageFunc(index, count)
	if err != nil {
		log.Info(err)
		return
	}
	if respCount == 0 || respCount < count {
		log.Info("no more data")
		return
	}
	for {
		index = index + respCount
		respCount, err = pageFunc(index, count)
		if err != nil {
			log.Info(err)
			break
		}
		if respCount == 0 || respCount < count {
			log.Info("no more data")
			break
		}
		if len(wait) > 0 {
			time.Sleep(time.Duration(wait[0]) * time.Millisecond)
		} else {
			time.Sleep(time.Second * 5)
		}
	}
}
